//这个文件用于注入导航栏

shanbay.nav = (function() {
  //闲聊
  var $chatting = $("<a href='javascript:void(0)'>闲聊</a>");

  this.enhance_nav = function() {
    shanbay.fix_nav_list("div#topnav .main-menu-sub-menu p");
    
    $("div#topnav div.menus a").each(function() {
      var txt = $(this).text();
      
      //修改小组链接到“我的小组”
      if (txt == "小组") {
        var $this = $(this);
        
        shanbay.await(function() {
          return typeof shanbay.user_info.in_team != "undefined";
        }, function() {
          var href;
          if (shanbay.user_info.in_team) {
            href = shanbay.user_info.team_href;
          } else {
            href = "http://www.shanbay.com/team/";
          }
          $this.prop("href", href).text("小组");
        });

      } else if (txt == "论坛") {
        $(this).prop("href", "http://www.shanbay.com/forum/misc/");
      }
    });

    //闲聊
    $("div#topnav div.right:first li#userhome").after($("<li/>").append($chatting));

    $chatting.click(function() {
      shanbay.chatting.show();
    });

    //查询英文解释
    //添加英文解释的展示层
    var $div = $("<div/>").prop("id", shanbay.generate_id("nav_query_en"));
    var $search_div = $("div#search").append($div);
    var $search_input = $search_div.find("input[name='query_word']");

    //查询方法
    var on_query = function() {
      $div.hide();
      var word = $search_input.val();
      $.getJSON("http://www.shanbay.com/api/word/" + word, function(data) {
        if (!data.voc || !data.voc.en_definitions)
          return;

        var $table = $("<table/>");
        var html = "";
        for ( var type in data.voc.en_definitions) {
          html += "<tr><th>" + type + ".</th><td>";
          var def = data.voc.en_definitions[type];
          for ( var i in def) {
            var index = parseInt(i) + 1;
            html += index + ": " + def[i];
            if (index != def.length)
              html += "<br/>";
          }
          html += "</td></tr>";
        }
        $table.html(html);
        $div.empty().append($table).show();
      });
    };

    //绑定
    $search_div.find("span.search").click(on_query);
    $search_input.keyup(function() {
      if (window.event.keyCode == 13) // Enter
        on_query();
    });
    $("body").click(function() {
      window.setTimeout(function() {
        if ($div.css("display") != "none")
          if ($search_div.find("div#search-content").css("display") == "none")
            $div.hide();
      }, 10);
    });

  };

  return this;
})();

$(function() {
  shanbay.nav.enhance_nav();
});
